package com.aote.mvc.event;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.aote.util.ExpressionHelper;
import com.browsesoft.ExtendElement;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;

/**
 * 动作工厂，负责管理并执行动作
 */
public class ActionFactory {
	/**
	 * 对应的组件
	 */
	private HTMLBasicComponent component;

	public ActionFactory(HTMLBasicComponent c) {
		this.component = c;
	}

	/**
	 * 执行动作
	 */
	public void doAction(String action, HttpServletRequest request, Map attrs) {
		throw new UnsupportedOperationException();
	}

	/**
	 * 获得动作配置
	 */
	private Element getConfig(String action) {
		// 找到动作配置，没有该动作配置元素，抛出异常
		List l = ExtendElement.findElementsByTagName(this.component
				.getElement(), "action", "name", action);
		if (l.size() == 0) {
			throw new RuntimeException("事件对应的动作没有找到：" + action);
		}
		return (Element) l.get(0);
	}

	/**
	 * 根据配置，产生动作
	 */
	private Action createAction(Element config) {
		// 根据配置的class属性，构造动作
		String str = config.getAttribute("class");
		try {
			return (Action) Class.forName(str).newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException("动作类没有默认构造函数：" + str);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("动作类不能构造：" + str);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("动作类没有找到：" + str);
		}
	}

	/**
	 * 判断组件中是否有此动作
	 */
	public boolean hasAction(String actionName) {
		LinkedList actions = ExtendElement.findElements(this.component
				.getElement(), "name", actionName);
		if (actions == null || actions.isEmpty()) {
			return false;
		}
		return true;
	}
}
